const Koa = require('koa')
global.app = new Koa()
const views = require('koa-views')
  // const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jsonp = require('koa-jsonp')

const index = require('./routes/index')
const users = require('./routes/users')
const api = require('./api/index')
const ajax = require('./ajax/index')
const mysql = require('./utils/mysql');
const common = require('./utils/comm');

const stuLogin = require('./api/stuLogin');
const token = require('./utils/token');
const co = require('co');
const render = require('koa-swig')
const regist = require('./api/stuAdd')
// const redis = require('./utils/redis');

// redis.set("a","text");
// redis.get("a",(err,value)=>{
//   console.log(value.ab)
// })

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
  }))
  // app.use(json())
app.use(jsonp())
app.use(logger())

app.use(require('koa-static')(__dirname + '/views'))
const dir = __dirname + '/views';

app.context.render = co.wrap(render({
  // ...your setting
  root: dir,
  autoescape: true,
  cache: 'memory', // disable, set to false
  ext: 'html',
  // locals: locals,
  // filters: "formatVersion",
  // tags: tags,
  // extensions: extensions,
  writeBody: true
}));
// app.use(views(__dirname + '/views', {
//     ext: 'html', //渲染文件后缀为 html
//     noCache: true, //开发环境下不设置缓存
//     watch: true //开发环境下观察模板文件的变化并更新，方便开发
//   }))

// app.use(require('koa-static')(__dirname + '/helsinki-blue'))
// app.use(views(__dirname + '/helsinki-blue', {
//     ext: 'html', //渲染文件后缀为 html
//     noCache: true, //开发环境下不设置缓存
//     watch: true //开发环境下观察模板文件的变化并更新，方便开发
//   }))


// logger
// app.use(async(ctx, next) => {
//   console.log(ctx.request.ip);
// })

//添加自定义中间件mysql
app.use(async(ctx, next) => {
  Object.assign(ctx, {
    mysql: mysql,
    COMM: common
  });
  await next();
  
});


app.use(ajax.routes(), ajax.allowedMethods())
app.use(stuLogin.routes(), stuLogin.allowedMethods());
app.use(regist.routes(), regist.allowedMethods());
app.use(token.routes(), token.allowedMethods())

// routes
app.use(index.routes(), index.allowedMethods())
  // app.use(users.routes(), users.allowedMethods())
app.use(api.routes(), api.allowedMethods())




module.exports = app



